package com.bobi.tfca.ui.mainnavigation.message.letter

import android.view.View
import android.widget.ImageView
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.bobi.tfca.network.ApiResponse
import com.bobi.tfca.network.api.MessageAPI
import com.bobi.tfca.network.response.MessageResponse
import com.bobi.tfca.util.LogUtil
import com.bobi.tfca.viewmodel.PublicViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

class LetterFragmentVM : ViewModel() {


    val letters by lazy {
        MutableLiveData(ArrayList<MessageResponse>())
    }

    /**
     * 查询所有信件，但是不会查询内容
     */
    fun findAllLetters(
        publicViewModel: PublicViewModel,
        letterFragment: LetterFragment,
        noDataIV: ImageView
    ) {
        publicViewModel.apply {
            request(MessageAPI::class.java).findAllLetters().getResponse {
                it.collect {
                    when (it) {
                        is ApiResponse.Error -> {
                            LogUtil.e(it.errMsg)
                        }

                        ApiResponse.Loading -> LogUtil.e("Loading")
                        is ApiResponse.Success -> {
                            withContext(Dispatchers.Main) {

                                if (it.data?.code == 200) {
                                    val list = it.data.data
                                    if (list != null && list.size > 0) {
                                        // 赋值
                                        letters.value = list as ArrayList<MessageResponse>
                                        noDataIV.visibility = View.GONE
                                    } else {
                                        // 如果没有数据，设置背景图片
                                        noDataIV.visibility = View.VISIBLE
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}